import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  const whiteList = ['/login', '/404']

  if (store.getters.token) {
    // 有 token
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log('触发了筛选过程')
        const routes = await store.dispatch('permission/filterRoutes', res.roles.menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
